import * as redisStore from 'koa-redis'
import { createClient } from "redis"
// const redis = require('redis')
import * as redis from "redis";
// const redis = require("redis")
// import { REDIS_CONF } from "./config/redis"
//进行配置

// const client = redis.createClient(REDIS_CONF.port, REDIS_CONF.host);
const client = redis.createClient({
    // url: REDIS_CONF.host,
    // url: REDIS_CONF.host
    url: "redis://127.0.0.1:6379/"
});


const options = {client: client, db: 1};

const store = redisStore(options);
client.on("error", (err:any) => {
    console.log("redis error", err);
})
client.on('ready', function (res:any) {
    console.log('client ready');
});
/**
 * redis set
 * @param {string} key key
 * @param {string} val val
 * @param {number} timeout 过期时间，单位 s
 */
 function set(key:string, val:string, timeout = 60 * 60 * 24 * 8 ) {
    if (typeof val === "object") {
        val = JSON.stringify(val)
    }
    client.set(key, val)
    client.expire(key, timeout,(err,reply) => {
        console.log("结束了？",key, timeout);
        console.log(err,reply);
        
        
    })
}


/**
 * redis get
 * @param {string} key key 
 */
function get(key:string) {
    const promise = new Promise((resolve, reject) => {
        client.get(key, (err, val) => {
                if (err) {
                    reject(err)
                    return
                }
                if (val == null) {
                    resolve(null)
                    return
                }
                try {
                    resolve(JSON.parse(val))
                } catch (err) {
                    resolve(val)
                }
            })
    })  

    return promise
}

const del = (key:string) =>  client.del(key)



client.on('connect', async function () {
    // set("var_1", "var_1_val");
    // var read_var=await get("var_1");
    // console.log("读取到的值："+read_var);
    // client.set("var_2", "var_2_val", function () {
    //     var read_var_2=client.get("var_2");
    //     console.log("第二次读取到的值："+read_var_2);
    // });
    // client.set("var_3", "var_3_val", function () {
    //     var read_var_3=client.get("var_3",function (err,reply) {
    //         console.log("第三次读取到的值：",err,reply);
    //     });
    // });
    // client.quit();
});




// client.quit()
export {
    set,
    get,
    del,
    client
}